﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using MMM.Core.Domain;
using ServiceStack.ServiceHost;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using MMM.Services.Base;
using MMM.Services.Operations;
using MMM.Services.Type;
using MMM.Core;
using MMM.Services.Response;
using ServiceStack.OrmLite;
using ServiceStack.ServiceInterface;


namespace MMM.Services
{

    public class RolePersionService : RestServiceBase<RolePermission>
    {
        public override object OnGet(RolePermission request)
        {
            var node = new modelNode() { id = Guid.Empty };

            addNode(node, request.RoleID);
            return node;
        }

        private void addNode(modelNode pnode, Guid? roleID)
        {
            IRepository<Module> ModuleRep = ApplicationContext.Container.GetInstance<IRepository<Module>>();
            IEnumerable<Module> modules = ModuleRep.GetAll(t => t.ParentID == pnode.id);
            var session = (MyUserSession)this.GetSession(false);
            if (modules.Count() > 0)
            {
                pnode.leaf = false;
                foreach (var item in modules)
                {
                    if (!session.IsAuthenticated)
                    {
                        if (item.Name == "配置管理")
                        {
                            continue;
                        }
                    }
                    var node = new modelNode { text = item.Name, id = item.Id, leaf = pnode.leaf, Image = "treeNode/" + item.Image, Name = item.Name, Value = 0, ModuleID = item.ParentID, expanded = true };
                    if (string.IsNullOrEmpty(item.Image))
                    {
                        node.Image = "treeNode/moduletpl";
                    }
                    pnode.children.Add(node);

                    addNode(node, roleID);

                }
            }
            addFun(pnode, roleID);
        }

        private void addFun(modelNode pnode, Guid? roleID)
        {
            IRepository<Function> FuncRep = ApplicationContext.Container.GetInstance<IRepository<Function>>();

            //获取功能模块
            var functions = this.GetCacheClient().Get<List<Function>>("functions");
            if (functions == null)
            {
                functions = FuncRep.GetAll().OrderBy(t => t.OrderIndex).ToList();
                this.GetCacheClient().Add<List<Function>>("functions", functions);
            }
            IDictionary<Guid?, int> dic = new Dictionary<Guid?, int>();


            if (roleID.HasValue)
            {
                //获取用的权限
                var dd = this.GetCacheClient().Get<List<UserPermission>>("dd");
                if (dd == null)
                {
                    var rep = ApplicationContext.Container.GetInstance<IRepository<UserPermission>>();
                    dd = rep.GetAll().ToList();
                    this.GetCacheClient().Add<List<UserPermission>>("dd", dd);
                }
                var items = dd.Where(t => t.RoleID == roleID.Value && t.Type == 1 && t.Value != 0);
                foreach (var item in items)
                {
                    dic.Add(item.FID, item.Value);
                }
            }



            foreach (var item in functions)
            {
                if (item.ModuleID == pnode.id && item.Value != 0)
                {
                    if (string.IsNullOrEmpty(item.Image))
                    {
                        item.Image = "gridtpl";
                    }
                    modelNode node = new modelNode();
                    node.iconCls = item.Image;
                    node.text = item.Name;
                    node.Url = item.Url;
                    node.ModuleID = item.ModuleID;
                    node.leaf = true;
                    node.Image = "treeNode/" + item.Image;
                    node.Value = item.Value;
                    node.id = item.Id;
                    node.Name = item.Name;
                    node.expanded = false;

                    if (item.Id.HasValue)
                    {
                        if (dic.ContainsKey(item.Id.Value))
                        {
                            node.ValueHad = dic[item.Id.Value];
                        }
                    }

                    pnode.children.Add(node);
                }
            }

        }
    }

    public class ModelNodeListService : RestServiceBase<ModelNodeList>
    {
        public override object OnPost(ModelNodeList request)
        {
            IRepository<UserPermission> PerRep = ApplicationContext.Container.GetInstance<IRepository<UserPermission>>();
            foreach (var item in request)
            {
                IEnumerable<UserPermission> userPers = PerRep.GetAll(t => t.RoleID == request.RoleID.Value && t.FID == item.id.Value);
                UserPermission userPer = null;
                if (userPers.Count() == 0)
                {
                    int maxIndex = 0;
                    if (PerRep.GetAll().Count() > 0)
                        maxIndex = PerRep.GetAll().Max(t => t.Index);
                    userPer = new UserPermission();
                    userPer.Id = Guid.NewGuid();
                    userPer.FName = item.Name;
                    userPer.FID = item.id;
                    userPer.RoleID = request.RoleID;
                    userPer.Type = 1;
                    userPer.Index = maxIndex + 1;
                    userPer.Value = item.ValueHad;

                    PerRep.Add(userPer);
                }
                else
                {
                    userPer = userPers.First();
                    userPer.Value = item.ValueHad;
                    PerRep.Update(userPer);
                }
            }
            this.GetCacheClient().Remove("functions");
            this.GetCacheClient().Remove("dd");
            return OperationResult<ModelNodeList>.SuccessRespose;
        }
    }


    public class modelNode : JsonNode<modelNode>
    {
        public modelNode()
        {
            Value = 0;
            ValueHad = 0;
        }
        /// <summary>
        /// 名称
        /// </summary>
        public string Name { get; set; }
        /// <summary>
        /// 模块ID
        /// </summary>
        public Guid? ModuleID { get; set; }
        /// <summary>
        /// 链接地址
        /// </summary>
        public string Url { get; set; }
        /// <summary>
        /// 图标
        /// </summary>
        public string Image { get; set; }
        /// <summary>
        /// 功能所有的权限
        /// </summary>
        public int Value { get; set; }

        /// <summary>
        /// 该角色拥有的权限
        /// </summary>
        public int ValueHad { get; set; }

        /// <summary>
        /// 
        /// </summary>
        public Guid? RoleID { get; set; }

    }

    [Serializable]
    [Route("/api/modelNode", "POST")]
    public class ModelNodeList : List<modelNode>
    {
        public Guid? RoleID { get; set; }
    };

}
